import { useEffect, useState } from 'react';
import { getTrendingMovies } from './appwrite';
import { TMDB_Movie, TMDB_MoviePage } from './types';
import MovieCard from './components/MovieCard';

getTrendingMovies().then((movies) => {
  console.log(movies);
});

async function getTMDBMovies() {
  const API_BASE_URL = 'https://api.themoviedb.org/3';

  const API_KEY = import.meta.env.VITE_TMDB_API_KEY;

  const API_OPTIONS = {
    method: 'GET',
    headers: {
      accept: 'application/json',
      Authorization: `Bearer ${API_KEY}`,
    },
  };

  const endpoint = `${API_BASE_URL}/discover/movie?sort_by=popularity.desc`;

  const response = await fetch(endpoint, API_OPTIONS);
  if (!response.ok) {
    throw new Error('Failed to fetch movies [response not ok]');
  }

  const data: TMDB_MoviePage = await response.json();
  // if(data.Response === 'False') {
  //   throw new Error('Failed to fetch movies [response not ok]');
  // }
  return data;
}

function App() {
  const [movieList, setMovieList] = useState<TMDB_Movie[]>([]);

  const fetchMovies = async () => {
    const TMDB_MoviesPage = await getTMDBMovies();
    console.log(TMDB_MoviesPage);
    setMovieList(TMDB_MoviesPage.results || []);
  };
  useEffect(() => {
    fetchMovies();
  }, []);

  return (
    <main>
      <div className="pattern"></div>
      <div className="wrapper">
        <header>
          <img src="./hero.png" alt="Hero Banner" />
          <h1>
            Find <span className="text-gradient">Movies</span> You'll Enjoy
            Without the Hassle
          </h1>
        </header>
        <section className="all-movies">
          <h2> All Movies</h2>
          <ul>
            {movieList.map((movie) => (
              <MovieCard key={movie.id} movie={movie} />
            ))}
          </ul>
        </section>
      </div>
    </main>
  );
}

export default App;
